<template>
  <form @submit.prevent="onSubmit" class="mt-3 flex gap-2">
    <input
      v-model="email"
      type="email"
      placeholder="输入邮箱"
      class="flex-1 rounded-full border-white/10 bg-white/5 text-white placeholder:text-white/40 focus:border-emerald-400 focus:ring-emerald-400 disabled:opacity-60"
      :disabled="loading"
      required
    />
    <button class="btn-primary" :disabled="loading">
      {{ loading ? '提交中...' : '订阅' }}
    </button>
  </form>
  <p v-if="message" class="text-sm mt-2">{{ message }}</p>
</template>

<script setup>
import { ref } from 'vue';
import { subscribeEmail } from '@/api/EmaillApi.js'; // 修正导入名，指向真实文件

const email = ref('');
const loading = ref(false);
const message = ref('');

const EMAIL_REGEX = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

const onSubmit = async () => {
  const value = (email.value || '').trim().toLowerCase();
  if (!value) {
    message.value = '请输入邮箱地址';
    return;
  }
  if (!EMAIL_REGEX.test(value)) {
    message.value = '邮箱格式不正确';
    return;
  }
  loading.value = true;
  message.value = '';
  try {
    const { data } = await subscribeEmail(value); // 传入字符串 email
    // 后端用业务 code 返回状态
    if (data?.code === 6666) {
      message.value = '订阅成功！我们会不定期发送优质内容。';
      email.value = '';
    } else if (data?.code === 4002) {
      // 幂等：将已存在视为“已订阅”
      message.value = '你已订阅过该邮箱，我们会不定期发送优质内容。';
      email.value = '';
    } else {
      message.value = data?.msg || '提交失败，请稍后重试';
    }
  } catch (err) {
    message.value = err?.response?.data?.msg || '网络异常，请稍后重试';
  } finally {
    loading.value = false;
  }
};
</script>